﻿import { Injectable,EventEmitter } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import { ApiService } from './app.service.api';
import { CookieConsent } from './app.service.cookie';

@Injectable()
export class AppServiceMembership {
    private _loginUrl = '/api/account/authenticate';
    private _registerUrl = '/api/account/register';
    repository: any = {};
    isLoggedIn: boolean = false;
    //store the URL so we can redirect after logging in
    redirectUrl: string;
    public showUserInfo$: EventEmitter<string>;
    constructor(private http: Http, private apiService: ApiService) {
        this.showUserInfo$ = new EventEmitter<string>();
    }

    login(user: any, completed: any, loginFailed?: any) {
        this.apiService.post(this._loginUrl, user, completed, this.loginFailed);
    }

    register(user: any, completed: any, registrationFailed?: any) {
        this.apiService.post(this._registerUrl, user, completed,this.registrationFailed);
    }

    saveCredentials(user: any) {
        //base64  编码
        let membershipData = window.btoa(user.username + ':' + user.password);
        this.apiService.header.set('Authorization', 'Basic ' + membershipData);
        this.repository = {
            loggedUser: {
                username: user.username,
                authdata: membershipData
            }
        };
        this.isLoggedIn = true;
        let cookie = new CookieConsent();
        cookie.setCookie("repository", this.repository, 1);
        this.showUserInfo$.emit(user.username);
    }

    removeCredentials() {
        this.repository = {};
        let cookie = new CookieConsent();
        cookie.deleteCookie("repository");
        this.apiService.header.set('Authorization', '');
    }
    loginFailed(response: any) {
        console.log(response);
    }

    registrationFailed() {
        console.log('Registration failed. Try again.');
    }

    isUserLoggedIn(): boolean{
        return this.repository.loggedUser || false;
    }

    logout(): void {
        this.isLoggedIn = false;
        this.repository.loggedUser = {};
    }
}